<template>
  <div>
    <el-dialog v-model="DelFlag" title="删除确认框" width="500">
      <span>确认删除菜品{{ DelFlagName }}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="DelFlag = false">取消</el-button>
          <el-button type="primary" @click="realDel"> 确认删除 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible" title="菜品操作" width="500">
      <el-form :model="form">
        <el-form-item label="菜品名称" :label-width="formLabelWidth">
          <el-input v-model="form.menuName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="菜品价格" :label-width="formLabelWidth">
          <el-input
            v-model="form.menuPrice"
            placeholder="请输入菜品价格"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="售卖状态" :label-width="formLabelWidth">
          <el-select-v2
            v-model="form.state"
            :options="options"
            placeholder="请选择售卖状态"
            size="large"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="/api/upload/img"
            :headers="tokenBody"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
            limit="1"
            ><el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.menuDescribe"
            placeholder="请输入菜品描述"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="CheckData"> 修改 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="InsertDialogFormVisible" title="新增菜品" width="500">
      <el-form :model="form">
        <el-form-item label="菜品名称" :label-width="formLabelWidth">
          <el-input v-model="form.menuName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="菜品价格" :label-width="formLabelWidth">
          <el-input
            v-model="form.menuPrice"
            placeholder="请输入菜品价格"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="售卖状态" :label-width="formLabelWidth">
          <el-select-v2
            v-model="form.state"
            :options="options"
            placeholder="Please select"
            size="large"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="/api/upload/img"
            :headers="tokenBody"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
            limit="1"
            ><el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.menuDescribe"
            placeholder="请输入菜品描述"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="InsertDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="InsertData"> 新增 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/menu">菜单信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="insert_button">
      <el-button type="primary" @click="InsertNewMenu">新增</el-button>
    </div>

    <el-table :data="tableData" height="70vh" style="width: 100%">
      <el-table-column prop="menuName" label="菜品名称" width="180" />
      <el-table-column prop="menuPrice" label="价格" width="180" />
      <el-table-column label="图片">
        <template #default="scope">
          <img :src="scope.row.menuPicture" style="height: 80px" />
        </template>
      </el-table-column>
      <el-table-column label="菜品描述" prop="menuDescribe"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.menuId, scope.row)"
            >Delete</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="handleCheck(scope.row.menuId, scope.row)"
            >操作</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="photoShowFlag">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageItem"
      :page-sizes="[100, 200, 300, 400]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { tr } from "element-plus/es/locale";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref([]);
const token = localStorage.getItem("shop_auth_token");
const page = ref(1);
const pageItem = ref(100);
const pageTotal = ref(0);
const menuName = ref("");
const DelFlag = ref(false);
const DelFlagName = ref("");
const fileList = ref<UploadUserFile[]>([]);
const InsertDialogFormVisible = ref(false);

const tokenBody = ref({
  token: token,
});
const options = [
  {
    label: "停售",
    value: 0,
  },
  {
    label: "起售",
    value: 1,
  },
];
const delFlag = ref("");
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
  fileList.value = [];
};
const InsertNewMenu = () => {
  /**
   * 新增按钮
   * */
  fileList.value = [];
  form.menuPrice = 0;
  form.menuName = "";
  form.menuPicture = "";
  form.state = 1;
  form.menuDescribe = "";
  InsertDialogFormVisible.value = true;
};
const InsertData = () => {
  const req = {
    menuName: form.menuName,
    menuPrice: form.menuPrice,
    state: form.state,
    menuPicture: form.img,
    menuDescribe: form.menuDescribe,
  };
  axios
    .post("/api/menu/insert", req, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新增成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "新增失败",
        });
      }
      InsertDialogFormVisible.value = false;
      getMenuData();
    })
    .catch((err) => {
      console.log(err);
    });
};
const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  const url = res.message;
  fileList.value = [];
  fileList.value.push({
    name: "hhe",
    url: res.message,
  });
  form.img = res.message;
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

const realDel = () => {
  axios
    .get("/api/menu/del/" + delFlag.value, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getMenuData();
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  DelFlag.value = false;
};

const getMenuData = () => {
  if (menuName.value.length == 0) {
    menuName.value = "";
    // console.log(menuName.value);
  }
  axios
    .get(
      "/api/menu/shopSelect/" +
        page.value +
        "/" +
        pageItem.value +
        "?menuName=" +
        menuName.value,
      {
        headers: {
          token: token,
        },
      }
    )
    .then((res) => {
      // console.log(res);
      tableData.value = res.data.message.list;
      pageTotal.value = res.data.message.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
getMenuData();
const form = reactive({
  menuName: "",
  menuPrice: 0,
  state: 1,
  img: "",
  menuPicture: "",
  menuId: "",
  menuDescribe: "",
});
const CheckData = () => {
  dialogFormVisible.value = false;
  const req = {
    menuId: form.menuId,
    menuName: form.menuName,
    menuPrice: form.menuPrice,
    menuPicture: form.img,
    state: form.state,
    menuDescribe: form.menuDescribe,
  };
  axios
    .post("/api/menu/update", req, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
      getMenuData();
    })
    .catch((err) => {
      console.log(err);
    });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageItem.value = val;
  getMenuData();
};
const handleDelete = (val: string, row) => {
  DelFlag.value = true;
  delFlag.value = val;
  DelFlagName.value = row.menuName;
  console.log(val);
};
const handleCheck = (val: string, row) => {
  console.log(val);
  dialogFormVisible.value = true;
  form.menuId = val;
  form.menuName = row.menuName;
  form.menuPrice = row.menuPrice;
  form.state = row.state;
  form.menuDescribe = row.menuDescribe ? row.menuDescribe : "";
  if (row.menuPicture != null) {
    form.img = row.menuPicture;
    fileList.value = [];
    fileList.value.push({
      name: "hhe",
      url: row.menuPicture,
    });
  } else {
    form.img = "";
    fileList.value = [];
  }
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.value = val;
  getMenuData();
};
</script>

<style lang="scss" scoped>
.insert_button {
  width: 100%;
  display: flex;
  justify-content: end;
}
</style>
